<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import Detail from './components/Detail.vue'
import { Table } from '@/components/Table'
import {
  purchaseIndex,
  purchaseDEL,
  purchaseSubmit,
  purchasePassed,
  goodsSelect,
  transportSelect,
  placestartSelect,
  getPayTypeList,
  getStatusList,
  purchaseSaleAdd
} from '@/api/common'
import { useTable } from '@/hooks/web/useTable'
import { purchaseType } from '@/api/common/types'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { ref, reactive } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useRouter } from 'vue-router'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
const appStore = useAppStoreWithOut()
const { wsCache } = useCache()
//用户权限数组
const userRlues = wsCache.get(appStore.getUserInfo).rlues
const userId = wsCache.get(appStore.getUserInfo).id
const checkRlues = (rlues) => {
  //检查权限
  if (userRlues.includes(rlues)) {
    return true
  } else {
    ElMessage.error('当前用户无权限操作，请联系管理员')
    return false
  }
}
const { t } = useI18n()
// console.log(userRlues)
// defineOptions({
//   name: 'PurchaseOrder'
// })

const { push } = useRouter()

const { register, tableObject, methods } = useTable<purchaseType>({
  getListApi: purchaseIndex,
  delListApi: purchaseDEL,
  response: {
    list: 'data',
    total: 'total'
  },
  defaultParams: {
    // find:
  },
  find: userRlues.includes('201') ? -1 : userId
})

const { getList, setSearchParams } = methods
getList()

const { emitter } = useEmitt()

useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      tableObject.currentPage = 1
    }
    getList()
  }
})
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'id',
    label: t('warehousingEntry.number'),
    search: {
      show: false
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'user.username',
    label: '制单人',
    search: {
      show: false
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'purchase_no',
    label: '采购单号',
    width: '120px',
    search: {
      show: false
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'goods_id',
    label: t('warehousingEntry.typeOfGoods'),
    table: {
      show: false
    },
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await goodsSelect({})
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        localStorage.setItem('goodsSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: false
    }
  },
  {
    field: 'goodsTypeName',
    label: t('warehousingEntry.typeOfGoods'),
    form: {
      show: false
    },
    detail: {
      show: true
    }
  },
  {
    field: 'transport',
    label: t('warehousingEntry.modeOfTransport'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await transportSelect({})
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.name
          })
        })
        localStorage.setItem('transportSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'placestart',
    label: t('warehousingEntry.origin'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await placestartSelect()
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        localStorage.setItem('placestartSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'shouhuo',
    label: t('purchaseOrderAddWrite.recipient'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'placeend',
    label: t('warehousingEntry.destination'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await placestartSelect()
        let list: any = []
        res.data.list.forEach((item) => {
          list.push({
            label: item.name,
            value: item.id
          })
        })
        localStorage.setItem('placestartSelectData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'taxrate',
    label: t('shippingOrderSettings.taxRate'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'remark',
    label: t('warehousingEntry.productNameRemarks'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'buytime',
    label: t('warehousingEntry.receivingDate'),
    search: {
      show: true,
      component: 'DatePicker',
      componentProps: {
        type: 'date'
      }
    },
    form: {
      show: false,
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'paytype',
    table: {
      show: false
    },
    label: t('warehousingEntry.paymentType'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await getPayTypeList({})
        let list: any = []
        for (let key in res.data) {
          list.push({
            label: res.data[key],
            value: key
          })
        }
        localStorage.setItem('payTypeListData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      show: false
    },
    detail: {
      span: 24,
      show: false
    }
  },
  {
    field: 'paytype_text',
    label: t('warehousingEntry.paymentType'),
    search: {
      show: false
    },
    form: {
      show: false
    },
    table: {
      show: false
    },
    detail: {
      span: 24,
      show: false
    }
  },
  {
    field: 'paytype_text',
    label: t('warehousingEntry.paymentType'),
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'servicefee',
    label: t('warehousingEntry.serviceCharge'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'freight',
    label: '代付运费',
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'rebate',
    label: t('warehousingEntry.factoryRebate'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'chajia',
    label: t('warehousingEntry.priceDifferenceOfGoods'),
    search: {
      show: false
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'status_text',
    label: t('purchaseOrder.auditStatus'),
    search: {
      show: true,
      component: 'Select',
      api: async () => {
        const res: any = await getStatusList({})
        let list: any = []
        for (let key in res.data) {
          list.push({
            label: res.data[key],
            value: key
          })
        }
        localStorage.setItem('statusListData', JSON.stringify(list))
        return list
      },
      componentProps: {
        filterable: true,
        options: []
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24,
      show: true
    }
  },
  {
    field: 'action',
    width: '150px',
    label: t('formDemo.operate'),
    form: {
      show: false
    },
    fixed: 'right',
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const AddAction = (rlues) => {
  if (checkRlues(rlues)) push('/salesModule/purchaseOrderAdd')
}

const delLoading = ref(false)
const getArr = (selections) => {
  let a = ''
  selections.map((v) => (a += v.id + ','))
  return a
}

const delData = async (row: purchaseType | null, multiple: boolean, rlus: string) => {
  if (!checkRlues(rlus)) return false
  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? getArr(selections) : (tableObject.currentRow?.id as string),
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}
const dialogTitle = ref('')
const dialogVisible = ref(false)

const detailTableData: any = reactive([])
const action = async (row: purchaseType, type: string, ruls: string) => {
  if (!checkRlues(ruls)) return false
  switch (type) {
    case 'Edit':
      {
        push(`/salesModule/purchaseOrder${type}?id=${row.id}`)
      }
      break
    case 'Submit':
      {
        ElMessageBox.confirm(t('common.examineMessage'), t('common.delWarning'), {
          confirmButtonText: t('common.delOk'),
          cancelButtonText: t('common.delCancel'),
          type: 'warning'
        }).then(async () => {
          const res = await purchaseSubmit('' + row.id)
          if (res) {
            ElMessage.success('提交成功')
            emitter.emit('getList', 'edit')
          }
        })
      }
      break
    case 'Passed':
      {
        ElMessageBox.confirm(`是否${t('purchaseOrder.passedReview')}?`, t('common.delWarning'), {
          confirmButtonText: t('common.delOk'),
          cancelButtonText: t('common.delCancel'),
          type: 'warning'
        }).then(async () => {
          const res = await purchasePassed('' + row.id)
          if (res) {
            ElMessage.success('审核成功')
            emitter.emit('getList', 'edit')
          }
        })
      }
      break
    case 'saleOrder':
      {
        if (row.has_sale != 1) {
          ElMessageBox.confirm(`是否转为销售单?`, t('common.delWarning'), {
            confirmButtonText: t('common.delOk'),
            cancelButtonText: t('common.delCancel'),
            type: 'warning'
          }).then(async () => {
            const res = await purchaseSaleAdd({
              purchase_id: row.id
            })
            if (res) {
              ElMessage.success('提交成功')
              emitter.emit('getList', 'edit')
            }
          })
        }
      }
      break
    case 'detail':
      {
        // dialogTitle.value = '详情'
        // dialogVisible.value = true
        // tableObject.currentRow = row
        // let goodsStr = row.goods.replace(/&quot;/g, '"')
        // let goodsArr: any = JSON.parse(goodsStr)
        // goodsArr.forEach((item, i) => {
        //   let pieceItem = {
        //     key: i + 1,
        //     title: `${t('warehousingEntryAddWrite.goodsEntry')} ${i + 1} ：`,
        //     gname: item.gname,
        //     goods_id: item.goods_id,
        //     worth: item.worth,
        //     price: item.price,
        //     quantity: item.quantity,
        //     room: item.room,
        //     colour: item.colour,
        //     length: item.length,
        //     width: item.width,
        //     high: item.high,
        //     weight: item.weight,
        //     remark: item.remark,
        //     total: item.total
        //   }
        //   detailTableData.push(pieceItem)
        // })

        // push({
        //   path: `/logistics/purchaseOrderDetail`,
        //   query: {
        //     id: row.id,
        //     detailSchema: JSON.stringify(allSchemas.detailSchema)
        //   }
        // })
        push(`/salesModule/purchaseOrderEdit?id=${row.id}&isDetail=true`)
      }
      break
    default:
      break
  }
}
// const userInfo = wsCache.get(appStore.getUserInfo)
// console.log(userInfo, '用户信息')
</script>

<template>
  <ContentWrap>
    <Search
      :model="{}"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction('22-1')">{{ t('exampleDemo.add') }}</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData(null, true, '22-3')">
        {{ t('exampleDemo.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.limit"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" @click="action(row, 'Submit', '22-2')" v-if="row.status == 0">
          {{ t('purchaseOrder.submitForReview') }}
        </ElButton>
        <ElButton type="warning" v-if="row.status == 1" @click="action(row, 'Passed', '22-5')">
          {{ t('purchaseOrder.passedReview') }}
        </ElButton>
        <ElButton
          type="primary"
          v-if="row.has_sale == 0 && row.status == 2"
          @click="action(row, 'saleOrder', '22-6')"
          >生成销售单</ElButton
        >
        <ElButton type="primary" v-if="row.status != 2" @click="action(row, 'Edit', '22-2')">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <ElButton type="success" @click="action(row, 'detail', '22-4')">
          {{ t('router.watch') }}
        </ElButton>
        <ElButton type="danger" v-if="row.status != 2" @click="delData(row, false, '22-3')">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <!-- <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Detail
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
      :table-data="detailTableData"
    />
  </Dialog> -->
</template>
